#include "Bonus.h"
#include "ShootEmUp.h"
#include "GameManager.h"
#include "MainCharacter.h"

using namespace Ogre;
using namespace std;

int Bonus::ID=0;
const char* Bonus::DEFAULT_NAME="bonus_";
const char* Bonus::DEFAULT_NODE_NAME="BonusNode";

Bonus::Bonus(BonusType _type)
:Item(Bonus::DEFAULT_NAME + StringConverter::toString(Bonus::ID)),
type(_type)
{
	Bonus::ID++;
	mSceneMgr = ShootEmUp::getSingleton().getSceneManager();
	initialize();
}

Bonus::~Bonus()
{}

void Bonus::initialize()
{
	moveSpeed = ShootEmUp::getSingleton().getScrollingSpeed()*2;
	string meshname;
	Real scalefactor(1);
	switch(type)
	{
	case SHIELD:
		meshname = "shield.mesh";
		scalefactor = 0.15f;
		break;
	case LIFE:
		meshname = "bonusLife.mesh";
		scalefactor = 6.f;
		break;
	}
	mEntity = mSceneMgr->createEntity(getName(), meshname);
	mEntity->setUserObject( this );

	mSceneNode = mSceneMgr->getSceneNode(Bonus::DEFAULT_NODE_NAME)->createChildSceneNode(Bonus::DEFAULT_NODE_NAME+string("_")+getName());
	Vector3 initialPosition( 
		Math::RangeRandom(ShootEmUp::WORLD_MIN.x, ShootEmUp::WORLD_MAX.x), 
		Math::RangeRandom(ShootEmUp::WORLD_MIN.y, ShootEmUp::WORLD_MAX.y), 
		ShootEmUp::WORLD_MAX.z
		);
	mSceneNode->setPosition( initialPosition );
	mSceneNode->scale( Vector3::UNIT_SCALE * scalefactor );
	mSceneNode->attachObject( mEntity );
}

void Bonus::collision(Item* _item)
{
	_item->collisionWithBonus( this );
}

void Bonus::collisionWithBullet(Bullet* _bullet)
{}

void Bonus::collisionWithEnemy(Enemy* _enemy)
{}

void Bonus::collisionWithMainCharacter(MainCharacter* _mainCharacter)
{
	_mainCharacter->collisionWithBonus( this );
}

void Bonus::collisionWithFish(Fish * _fish)
{}

void Bonus::collisionWithBonus(Bonus* _bonus)
{}

void Bonus::collisionWithWeapon(Weapon* weapon)
{}

bool Bonus::frameStarted(const Ogre::FrameEvent& evt)
{
	move();
	return true;
}

bool Bonus::move(void)
{
	if ( mSceneNode->getPosition().z > (ShootEmUp::WORLD_MIN.z - 100) )
	{
		mSceneNode->translate(Vector3::NEGATIVE_UNIT_Z * moveSpeed);
		return true;
	}
	GameManager::getSingleton().destroyBonus( this );
	return false;
}

void Bonus::reset()
{
	Vector3 initialPosition( 
		Math::RangeRandom(ShootEmUp::WORLD_MIN.x, ShootEmUp::WORLD_MAX.x), 
		Math::RangeRandom(ShootEmUp::WORLD_MIN.y, ShootEmUp::WORLD_MAX.y), 
		ShootEmUp::WORLD_MAX.z
		);
	mSceneNode->setPosition( initialPosition );
	if ( mEntity->isAttached() )
		mEntity->getParentSceneNode()->detachObject( mEntity );
	mSceneNode->attachObject( mEntity );
}